package com.example.app.pages.main.login.viewModel

import retrofit2.HttpException
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.app.data.bean.BaseResponseData
import com.example.app.data.bean.UserInfo
import com.example.app.network.api.AccountService
import com.example.app.network.api.UserService
import com.example.app.viewmodel.MainViewModel
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.delay

class LoginViewModel(var mainViewModel: MainViewModel) : ViewModel() {
    fun request_login(
        Username: String,
        Password: String
    ): Deferred<BaseResponseData<UserInfo>> {
        return viewModelScope.async {
            
            try {
                var result = viewModelScope.async {
                    UserService.service.login(
                        Username,
                        Password
                    )
                }.await()
                
                mainViewModel.requestHandler(result)
                return@async result
            } catch (e: HttpException) {
                var result = viewModelScope.async {
                    BaseResponseData<UserInfo>(
                        code = e.code(),
                        data = null,
                        msg = e.message.toString()
                    )
                }.await()
                
                mainViewModel.requestHandler(result)
                return@async result
            }
        }
    }
}